package org.infodavid.common.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import org.infodavid.common.IBuilder;
import org.infodavid.common.dto.IPersonListItem.EPersonTitle;
import org.infodavid.common.ejb.UserBean;
import org.infodavid.common.model.components.IEMail;

/**
 * The Class UserTest.
 */
public class UserTest extends AbstractBeanTest<IUser> {

	/** The person test. */
	private final PersonTest personTest = new PersonTest(this);

	/** The group test. */
	private final GroupTest groupTest = new GroupTest(this);

	/**
	 * Instantiates a new test.
	 * @param mainTest the main test
	 */
	public UserTest(final AbstractPersistenceTest mainTest) {
		super(mainTest);
	}

	/**
	 * Instantiates a new user test.
	 */
	public UserTest() {
		super();
	}

	/**
	 * Populate.
	 * @param count the count
	 * @return the collection< test data>
	 * @throws Exception the exception
	 */
	@Override
	protected List<IUser> doCreate(final int count) throws Exception {
		final IBuilder<IUser> builder = ModelFactory.getInstance().getBuilder(IUser.class);
		final IBuilder<IEMail> emailBuilder = ModelFactory.getInstance().getBuilder(IEMail.class);
		final Iterator<IPerson> persons = personTest.populate(count).iterator();
		final Iterator<IUserGroup> groups = groupTest.populate(count).iterator();
		final List<IUser> items = new ArrayList<IUser>(count);
		long key;
		IUser item;
		IEMail email;

		for (int i = 0; i < count; i++) {
			item = builder.create();
			key = System.nanoTime();

			item.setArchived(false);
			item.setName("item-" + key);
			item.setLastName("lastname-" + key);
			item.setFirstName("firstname-" + key);
			item.setTitle(EPersonTitle.values()[RAND.nextInt(EPersonTitle.values().length)]);
			item.setComment("comment-" + key);
			item.setExpirationDate(new DateTime());
			item.setLastIP("127.0.0.1");
			item.setPassword("password-" + key);
			item.setPseudonym("pseudo-" + key);
			item.setPerson(persons.next());
			item.addGroup(groups.next());
			item.setLocale(Locale.FRANCE);
			item.setTimeZone(DateTimeZone.forOffsetHours(+1));

			email = emailBuilder.create();

			email.setValue(item.getName() + "@domain.com");
			item.setEmail(email);

			item.getProperties().addData("key1", "value1");
			item.getProperties().addData("key2", "value2");

			items.add(item);
		}

		return items;
	}

	/**
	 * See super class or interface. (non-Javadoc)
	 * @see org.infodavid.common.model.AbstractBeanTest#getEntityClass()
	 */
	@Override
	public Class<UserBean> getEntityClass() {
		return UserBean.class;
	}

	/**
	 * See super class or interface. (non-Javadoc)
	 * @see org.infodavid.common.model.AbstractBeanTest#getEntityName()
	 */
	@Override
	public String getEntityName() {
		return IUser.class.getSimpleName();
	}
}
